<?php

namespace App\Cache;
/**
 * This file is part of Hyperf Mall.
 *
 * @link     https://gitee.com/scwlkj/hypref_mall
 * contact  hyperf_mall@163.com
 */
use App\Common\DataConvert;
use App\Model\Member\MemberModel;
use App\Utils\Log;
use App\Utils\Rsa;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

class TokenCache extends Cache
{
    public static $cacheKeyPx = 'auth_token';

    public $type;   //登录类型

    const TYPE_PLATFORM = 1;    //后台管理员
    const TYPE_APP = 2;         //前台用户
    const TYPE_PC = 3;         //PC端用户

    /**
     * 有效期有效期  (秒数)
     */
    const EXPIRED_TIME = 60 * 60 * 24 * 2;

    /**
     * 剩余多长时间到期重置缓存 (秒数)
     */
    const SURPLUS_TIME_RESET = 60 * 60 * 12;

    /**
     * @param int $type
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function __construct(int $type)
    {
        $this->type = $type;
        parent::__construct();
    }

    /**
     * Notes:获取缓存信息
     * @param string $token
     * @return array|null
     */
    public function getInfo(string $token): ?array
    {
        $nowTime = time();
        $key = $this->get(static::getCacheKey($this->type, $token));
        if ($key === false) {
            return null;
        }

        $data = DataConvert::decode(Rsa::getInstance()->privDecrypt($key));
        // 两天时间缓存失效
        if ($data['create_time'] + self::EXPIRED_TIME <= $nowTime) {
            $this->remove($token);
            return null;
        }

        // 12小时以内重置缓存
        if (($nowTime - $data['create_time']) <= self::SURPLUS_TIME_RESET) {
            $data['create_time'] = $nowTime;
            $this->createToken($data);
        }

        return $data;
    }

    /**
     * Notes: 创建或更新token
     * @param array $data
     * @return string
     */
    public function createToken(array $data): string
    {
        $data = array_only($data,$this->getTokenFields());
        $data['create_time'] = time();
        $encrypt = Rsa::getInstance()->publicEncrypt(DataConvert::encode($data));

        $token = $data['id'] . '-' . md5($this->type . $data['id']);
        $this->set(
            static::getCacheKey($this->type, $token),
            $encrypt,
            self::EXPIRED_TIME
        );
        return $token;
    }

    /**
     * 删除缓存
     * @param string $token
     * @return int
     */
    public function remove(string $token): int
    {
        return $this->del(static::getCacheKey($this->type, $token));
    }

    /**
     * 整理key
     * @param int $type
     * @param string $token
     * @return string
     */
    protected static function getCacheKey(int $type, string $token): string
    {
        return get_saas_id() . ':' . static::$cacheKeyPx . ':' . $type . ':' . $token;
    }

    public function getTokenFields()
    {
        return ['id','level','username','image','sex','tel','country','province','city','area','birth'];
    }


}
